from flask import Blueprint,jsonify,request
import json
import functools

from utils.rbac import rbac


bp_ziyuan =Blueprint('ziyuan',__name__)

from  utils.db import db1
from comm import get_data

@bp_ziyuan.route('/ziyuan')
def ziyuan():
    uid = request.args.get('uid')

    # sql = "select resource.name,resource.id from resource left join resource_user as u on u.resource_id = resource.id where users_id = %d" % int(uid)

    sql = "select * from resource"

    res = db1.find_all(sql)

    return jsonify({'code':200,'list':res})

@bp_ziyuan.route('/quanxian',methods=["POST"])
def quanxian():

    data = get_data()
    sql = "delete from resource_user where users_id  = %d"  % int(data['uid'])
    db1.update(sql)
    for i in json.loads(str(data['resource_id'])):
        sql = "insert into resource_user(resource_id,users_id) values(%d,%d)" % (int(i),int(data['uid']))
        db1.update(sql)

    rbac.update_role_resource(data['uid'],data['rescource_id'])
    return jsonify({'code':200,'mes':'添加成功'})







@bp_ziyuan.route('/getzi')
def getzi():
    uid = request.args.get('uid')
    sql = "select resource_id from resource_user where users_id = %d" % int(uid)

    res = db1.find_all(sql)

    return jsonify({'code':200,'list':res})


# 获取全部资源
@bp_ziyuan.route('/ziyuanall')
def ziyuanall():
    # sql1 = " select r.name from resource  as r  left join resource_user as ur on r.id=ur.resource_id where ur.users_id is NULL and r.type=1;"

    sql = "select * from resource"

    res1 = db1.find_all(sql)

    return jsonify({'code':200,'list':res1})





@bp_ziyuan.route('/getrole')
def getrole():
    sql = "select * from role"

    res = db1.find_all(sql)

    return jsonify({'code':200,'list':res})





@bp_ziyuan.route("/updatePermission",methods=["POST"])
def updatePermission():
    data = get_data()
    sql = "delete from role_resource where role_id=%d"%int(data["id"])
    db1.update(sql)
    for i in json.loads(data["list"]):
        sql1 = "insert into role_resource(role_id,resource_id) values(%d,%d)"%(int(data["id"]),int(i["id"]))
        db1.update(sql1)
    return jsonify({"code":200,"msg":"权限修改成功"})





@bp_ziyuan.route("/permission")
def permission():
    sql = "select id,name from resource"
    res = db1.find_all(sql)
    print(res)
    return jsonify({"code":200,"list":res})



@bp_ziyuan.route("/get_user_resource")
def get_user_resource():
    roleid = request.args.get("roleid")
    sql = "select r.id,r.name from resource as r right join role_resource as rr on r.id=rr.resource_id where role_id=%d" % int(roleid)
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})



# 用户配置角色





